package nio.serverdemo01;



import nio.NioUtils;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * NioServerDemo 阻塞模式
 *
 * @author chenxin
 * @date 2022/05/17 17:18
 **/
public class IoServerDemo {

    // 弊端：open.accept()没有连接时会一直阻塞，线程做不了其他事情 只能一直等待连接 效率很低
    public static void main(String[] args) throws IOException {
        ByteBuffer buffer = ByteBuffer.allocate(16);

        ServerSocketChannel open = ServerSocketChannel.open();
        open.bind(new InetSocketAddress(8080));
        List<SocketChannel> channels = new ArrayList<>();
        while(true){
            System.out.println("connecting ....");

            // 阻塞方法， 线程停止运行
            SocketChannel sc = open.accept();

            System.out.println("connected");

            channels.add(sc);

            for (SocketChannel channel : channels) {
                System.out.println("before read ... "+channel);

                // 阻塞方法，线程停止运行
                // 等待读取
                channel.read(buffer);

                buffer.flip();

                System.out.println("buffer:"+ NioUtils.getString(buffer));

                buffer.clear();

                System.out.println("after read ..."+channel);



            }


        }


    }



}